package com.calsoft.Hops_Mobile_Tablet;

import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.*;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.calsoft.Hops_Mobile_Tablet.base.App;
import com.calsoft.Hops_Mobile_Tablet.base.NavDrawerMenuArrayAdapter;
import com.calsoft.Hops_Mobile_Tablet.component.AlertDialogFragment;
import com.calsoft.Hops_Mobile_Tablet.util.SessionManager;
import com.calsoft.Hops_Mobile_Tablet.util.SharedPrefs;

public class MainActivity extends FragmentActivity implements AlertDialogFragment.AlertDialogListener {

    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    private String[] mMenuTitles;

    private SessionManager sessionManager;

    public static final String SET_LOCATION_CITY = "com.calsoft.hops.mobile.tablet.set.location.city";
    private SharedPrefs sPrefs;
    private int currentPage = App.APP_MENU_HOME;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sessionManager = new SessionManager(getApplicationContext());
        sessionManager.checkLogin();

        sPrefs = new SharedPrefs(getApplicationContext());

        mTitle = mDrawerTitle = getTitle();
        mMenuTitles = getResources().getStringArray(R.array.menu_array);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        // set a custom shadow that overlays the main content when the drawer opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        // set up the drawer's list view with items and click listener
        mDrawerList.setAdapter(new NavDrawerMenuArrayAdapter(getApplicationContext(), mMenuTitles));
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        // enable ActionBar app icon to behave as action to toggle nav drawer
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the sliding drawer and the action bar app icon
        mDrawerToggle = new ActionBarDrawerToggle(
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description for accessibility */
                R.string.drawer_close  /* "close drawer" description for accessibility */
        ) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);
    }

    @Override
    protected void onResume() {
        super.onResume();
        currentPage = sPrefs.getInt(SharedPrefs.CURRENT_PAGE, 0);
        selectItem(currentPage);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        switch (currentPage){
            case App.APP_MENU_OP_TOURS: inflater.inflate(R.menu.op_tours, menu);
                break;
//            case App.APP_MENU_LOCATION: inflater.inflate(R.menu.location, menu);
//                break;
        }
        return super.onCreateOptionsMenu(menu);
    }

    /* Called whenever we call invalidateOptionsMenu() */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the nav drawer is open, hide action items related to the content view
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        switch (currentPage){
            case App.APP_MENU_OP_TOURS: menu.findItem(R.id.action_category_filter).setVisible(!drawerOpen);
                break;
//            case App.APP_MENU_LOCATION: menu.findItem(R.id.action_change_country).setVisible(!drawerOpen);
//                break;
        }
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // The action bar home/up action should open or close the drawer.
        // ActionBarDrawerToggle will take care of this.
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action buttons
        switch (item.getItemId()) {
            case R.id.action_category_filter:
                OpToursFragment opToursFragment = (OpToursFragment) getSupportFragmentManager().findFragmentById(R.id.content_frame);
                opToursFragment.showCategoryFilterDialog();
                return true;
//            case R.id.action_change_country:
//                LocationFragment locationFragment = (LocationFragment) getSupportFragmentManager().findFragmentById(R.id.content_frame);
//                locationFragment.changeCountry();
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onDialogPositiveClick(DialogFragment dialog, int dialogType, String strArg) {
        dialog.dismiss();
        switch(dialogType){
            case App.DIALOG_LOG_OUT:
                sessionManager.logoutUser();
                break;
            case App.DIALOG_SET_CURRENT_LOCATION:
                sPrefs.putString(SharedPrefs.CURRENT_LOCATION, strArg);
                LocationFragment locationFragment = (LocationFragment) getSupportFragmentManager().findFragmentById(R.id.content_frame);
                locationFragment.changeCurrentLocation(strArg);
                break;
        }
    }

    @Override
    public void onDialogNegativeClick(DialogFragment dialog) {
        dialog.dismiss();
        selectItem(currentPage);
    }


    /* The click listener for ListView in the navigation drawer */
    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
        }
    }

    private void selectItem(int position) {
        if (position != App.APP_MENU_LOG_OUT) {
            currentPage = position;
            sPrefs.putInt(SharedPrefs.CURRENT_PAGE, currentPage);
            invalidateOptionsMenu();
        }
        switch (position) {
            case App.APP_MENU_HOME:
                setHomeFragment(position);
                break;
            case App.APP_MENU_OP_TOURS:
                setOpToursFragment(position);
                break;
            case App.APP_MENU_WISH_LIST:
                setWishListFragment(position);
                break;
            case App.APP_MENU_DEALS:
                setDealsFragment(position);
                break;
            case App.APP_MENU_LOCATION:
                setLocationFragment(position);
                break;
            case App.APP_MENU_GUESTS:
                setGuestsFragment(position);
                break;
            case App.APP_MENU_LOG_OUT:
                setLogOutFragment(position);
                break;
        }
    }

    private void updateItemTitleDrawer(int position) {
        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        setTitle(mMenuTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    }

    private void foo(int position) {
        // update the main content by replacing fragments
        Fragment fragment = new PlaceHolderFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
        updateItemTitleDrawer(position);
    }

    private void setLogOutFragment(int position) {
        DialogFragment dialog = new AlertDialogFragment(App.DIALOG_LOG_OUT, "Would you like to log out?", "");
        dialog.show(getSupportFragmentManager(), "AlertDialogFragment");
    }

    private void setGuestsFragment(int position) {
        Fragment fragment = new GuestsFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
        updateItemTitleDrawer(position);
    }

    private void setLocationFragment(int position) {
        Fragment fragment = new LocationFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
        updateItemTitleDrawer(position);
    }

    private void setDealsFragment(int position) {
        Fragment fragment = new DealsFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
        updateItemTitleDrawer(position);
    }

    private void setWishListFragment(int position) {
        // update the main content by replacing fragments
        Fragment fragment = new WishListFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
        updateItemTitleDrawer(position);
    }

    private void setOpToursFragment(int position) {
        // update the main content by replacing fragments
        Fragment fragment = new OpToursFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
        updateItemTitleDrawer(position);
    }

    private void setHomeFragment(int position) {
        Fragment fragment = new HomeFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
        updateItemTitleDrawer(position);
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
        invalidateOptionsMenu();
    }

}
